import { setToken, getToken, removeToken, setTime, removeTime } from '@/utils/auth'
import { login, getUserInfo, getUserDetailInfo } from '@/api/user'
import { resetRouter } from '@/router'

const state = {
  token: getToken(),
  userInfo: {}
}
const mutations = {
  SET_TOKEN: (state, val) => {
    state.token = val
    setToken(val)
  },
  REMOVE_TOKEN: (state, val) => {
    state.token = ''
    removeToken()
    removeTime()
  },
  SET_USERINFO(state, val) {
    state.userInfo = val
  },
  REMOVE_USERINFO(state, val) {
    state.userInfo = {}
  },
  SET_RESULTINFO(state, val) {
    state.userInfo = { ...state.userInfo, ...val }
  },
}
const actions = {
  async login(context, val) {
    try {
      let result = await login(val);
      context.commit('SET_TOKEN', result)
      setTime(new Date())
      return '登陆成功!'
    } catch (error) {
      return Promise.reject(new Error('登陆失败!!!'))
    }
  },

  logout(context) {
    context.commit('REMOVE_TOKEN')
    context.commit('REMOVE_USERINFO')
    resetRouter()
    context.commit('permission/SET_ROUTES', [], { root: true })
    return true
  },

  async getUserInfo({ dispatch, commit }) {
    let result = await getUserInfo()
    commit('SET_USERINFO', result)
    dispatch('getUserDetailInfo', result.userId)
    return result
  },

  async getUserDetailInfo({ commit }, id) {
    let result = await getUserDetailInfo(id)
    commit('SET_RESULTINFO', result)
  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}